#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSerialPort/QSerialPortInfo>
#include <QtSerialPort/QSerialPort>
#include <QMessageBox>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileDialog>
#include <QTextCodec>
#include <QMimeDatabase>
#include <QScrollBar>

// // 封装串口设置函数
// void MainWindow::setupSerialPort() {
//     QSerialPort::BaudRate baudRate;
//     QSerialPort::DataBits dataBits;
//     QSerialPort::StopBits stopBits;
//     QSerialPort::Parity checkBits;

//     // 获取串口波特率
//     baudRate = getBaudRate(ui->baundrateCb->currentText());
//     // 获取串口数据位
//     dataBits = getDataBits(ui->databitCb->currentText());
//     // 获取串口停止位
//     stopBits = getStopBits(ui->stopbitCb->currentText());
//     // 获取串口奇偶校验位
//     checkBits = getCheckBits(ui->checkbitCb->currentText());

//     // 初始化串口属性
//     // serialPort->setPortName(ui->serailCb->currentText());
//     // serialPort->setBaudRate(baudRate);
//     // serialPort->setDataBits(dataBits);
//     // serialPort->setStopBits(stopBits);
//     // serialPort->setParity(checkBits);
// }

// 获取波特率
QSerialPort::BaudRate MainWindow::getBaudRate(const QString& text) {
    if (text == "1200") return QSerialPort::Baud1200;
    if (text == "2400") return QSerialPort::Baud2400;
    if (text == "4800") return QSerialPort::Baud4800;
    if (text == "9600") return QSerialPort::Baud9600;
    if (text == "19200") return QSerialPort::Baud19200;
    if (text == "38400") return QSerialPort::Baud38400;
    if (text == "57600") return QSerialPort::Baud57600;
    if (text == "115200") return QSerialPort::Baud115200;
    return QSerialPort::Baud9600; // 默认值
}

// 获取数据位
QSerialPort::DataBits MainWindow::getDataBits(const QString& text) {
    if (text == "5") return QSerialPort::Data5;
    if (text == "6") return QSerialPort::Data6;
    if (text == "7") return QSerialPort::Data7;
    if (text == "8") return QSerialPort::Data8;
    return QSerialPort::Data8; // 默认值
}

// 获取停止位
QSerialPort::StopBits MainWindow::getStopBits(const QString& text) {
    if (text == "1") return QSerialPort::OneStop;
    if (text == "1.5") return QSerialPort::OneAndHalfStop;
    if (text == "2") return QSerialPort::TwoStop;
    return QSerialPort::OneStop; // 默认值
}

// 获取校验位
QSerialPort::Parity MainWindow::getCheckBits(const QString& text) {
    if (text == "none") return QSerialPort::NoParity;
    if (text == "奇校验") return QSerialPort::OddParity;
    if (text == "偶校验") return QSerialPort::EvenParity;
    return QSerialPort::NoParity; // 默认值
}

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow),m_isSendingFile(false),workerThread(new QThread(this))
{
    ui->setupUi(this);

    workerThread = new QThread(this);
    worker = new class worker(&serialMutex);//不要设置parent
    //sendcount = new SendCountUpdater(serialPort, &serialMutex, lblSendNum, this);

    worker->moveToThread(workerThread);
    connect(workerThread, &QThread::finished, worker, &QObject::deleteLater);//线程结束 自动删除

    connect(worker,&worker::sendBytesWritten,this,&MainWindow::updateSendCount);//发送计数值
    connect(this, &MainWindow::serialDataSend, worker, &worker::sendData);//主通知子发送数据
    connect(worker, &worker::sendResultTO, this, &MainWindow::onDataReceivedFromWorker);//主收到数据结果
    connect(worker,&worker::portOpened,this,&MainWindow::handlePortOpened);//注释掉串口打开无反应
    connect(worker,&worker::errorOccurred,this,&MainWindow::handleError);//串口错误

    connect(this,&MainWindow::requestSendFile,worker,&worker::sendFile);//发送文件
    connect(this,&MainWindow::requestCancelFile,worker,&worker::cancelFileTransfer);//取消发送文件
    connect(worker,&worker::fileProgress,this,&MainWindow::updateFileProgress);
    connect(worker,&worker::fileTransferFinished,this,&MainWindow::onFileTransferFinished);
    workerThread->start();

    sendEmptyPrompted = false; // 初始化标志位为 false

    // 发送、接收计数清零
    sendNum = 0;
    recvNum = 0;
    // 状态栏
    QStatusBar* sBar = statusBar();
    // 状态栏的收、发计数标签
    lblSendNum = new QLabel(this);
    lblRecvNum = new QLabel(this);
    lblPortState = new QLabel(this);
    lblPortState->setText("Connected");
    //lblPortState->setText(serialPort->portName() + " CLOSED");？？？
    //设置串口状态标签为绿色 表示已连接状态
    lblPortState->setStyleSheet("color:red");

    // 设置标签最小大小
    lblSendNum->setMinimumSize(100, 20);
    lblRecvNum->setMinimumSize(100, 20);
    lblPortState->setMinimumSize(550, 20);
    setNumOnLabel(lblSendNum, "S: ", sendNum);
    setNumOnLabel(lblRecvNum, "R: ", recvNum);
    // 从右往左依次添加
    sBar->addPermanentWidget(lblPortState);
    sBar->addPermanentWidget(lblSendNum);
    sBar->addPermanentWidget(lblRecvNum);


    findSerial();

    //定时查找串口是否有更新
    timSerial = new QTimer(this);

    connect(timSerial, /*&QTimer::timeout*/SIGNAL(timeout()), this, SLOT(findSerial()));
    timSerial->start(500);
    // 定时发送-定时器
    timSend = new QTimer(this);

    connect(timSend, /*&QTimer::timeout*/SIGNAL(timeout()), this, SLOT(on_sendBt_clicked()));

}

void MainWindow::onDataReceivedFromWorker(const QByteArray &result){
    // 处理从worker接收到的数据
    qDebug() << "主线程接收到worker发送的数据：" << result;

    // 接收字节计数
    recvNum += result.size();
    // 状态栏显示计数值
    setNumOnLabel(lblRecvNum, "R: ", recvNum);

    QString str_rev = formatReceivedData(result);
    ui->recvEdit->moveCursor(QTextCursor::End);
    ui->recvEdit->insertPlainText(str_rev);
    auto* scrollbar = ui->recvEdit->verticalScrollBar();
    if (scrollbar) {
        scrollbar->setValue(scrollbar->maximum());
    }
}
void MainWindow::handlePortOpened(bool success,const QString &message)
{
    if(success){
        ui->openBt->setText("关闭串口");
        // 让端口号下拉框不可选，避免误操作（选择功能不可用，控件背景为灰色）
        ui->serailCb->setEnabled(false);
        lblPortState->setText(message);
        lblPortState->setStyleSheet("color:green");
    }else{
        ui->openBt->setText("打开串口");
        ui->serailCb->setEnabled(true);
        lblPortState->setText(message);
        lblPortState->setStyleSheet("color:red");
        ui->progressBar->setValue(0);//为了发送文件过程中串口突然断开情况下 将文件进度条设置为0
        // if(!message.isEmpty() && message != "串口已关闭") 和handleError的弹窗重复
        // {
        //     QMessageBox::critical(this,"错误提示",message);
        // }
    }
}
// 封装接收数据格式化函数
QString MainWindow::formatReceivedData(const QByteArray& result) {
    QString str_rev;
    if (ui->chk_rev_hex->isChecked())
    {
        QString hexStr = result.toHex(' ').toUpper();//自动添加空格
        if (ui->chk_rev_time->isChecked())
        {
            hexStr.prepend(QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss] ")).append("\r\n");
        }
        str_rev = hexStr.append(" ");
    }
    else
    {
        //文本显示处理
        str_rev =QString::fromUtf8(result);
        if (ui->chk_rev_time->isChecked())
        {
            str_rev.prepend(QDateTime::currentDateTime().toString("[yyyy-MM-dd hh:mm:ss] ")).append("\r\n");
        }
    }
    //换行处理
    if (ui->chk_rev_line->isChecked())
    {
        str_rev += "\r\n";
    }
    return str_rev;
}

void MainWindow::handleUpdateLabel(const QString& text)
{
    lblSendNum->setText(text);
}

void MainWindow::handleResults(QString result) {
    qDebug() << "主线程收到结果数据 ：" << result << "线程id: " << QThread::currentThread();
    // 更新界面
    ui->recvEdit->moveCursor(QTextCursor::End);
    ui->recvEdit->insertPlainText(result);

    // 自动滚动 auto?
    QScrollBar* scrollbar = ui->recvEdit->verticalScrollBar();
    if (scrollbar)
        scrollbar->setValue(scrollbar->maximum());
}
MainWindow::~MainWindow()
{
    // 断开所有信号槽连接
    if (worker)
    {
        delete worker;
        worker = nullptr;
    }

    if (workerThread)
    {
        workerThread->quit();
        workerThread->wait();
        delete workerThread;
        workerThread = nullptr;
    }
    delete ui;
}

void MainWindow::handleError(const QString &error)
{
    static bool isErrorShowing = false;
    static QString lastError;
    static QDateTime lastErrorTime;

    if(isErrorShowing) return;

    if(error == lastError && lastErrorTime.secsTo(QDateTime::currentDateTime()) < 1){
        return;
    }
    if(timSend->isActive())
    {
        timSend->stop();
    }
    // if(FileSendTimer->isActive() && FileSendTimer)
    // {
    //     FileSendTimer->stop();
    // }
    ui->chkTimSend->setChecked(false);
    ui->txtSendMs->setEnabled(true);

    // 1. 在状态栏显示错误信息
    lblPortState->setText("错误: " + error);
    lblPortState->setStyleSheet("color:red");

    lastError = error;
    lastErrorTime = QDateTime::currentDateTime();

    isErrorShowing = true;
    // 2. 弹出错误提示框
    QMessageBox::warning(this, "串口错误", error);
    isErrorShowing = false;

    // 3. 自动恢复UI状态
    ui->openBt->setText("打开串口");
    QMetaObject::invokeMethod(worker, "closePort", Qt::QueuedConnection);
    ui->serailCb->setEnabled(true);

    // 4. 记录到日志文件（可选）
    qDebug()<<("ERROR: " + QDateTime::currentDateTime().toString() + " - " + error);
}

/*处理串口错误函数*/
//void MainWindow::handleSerialError(QSerialPort::SerialPortError error) {

        //     qDebug() << "Received serial port error:" << error;

    //     if (error == QSerialPort::ResourceError || error == QSerialPort::PermissionError || error == QSerialPort::DeviceNotFoundError || error == QSerialPort::NotOpenError)
    //     {
    //         // 停止自动发送定时器
    //         if (timSend->isActive())
    //         {
    //             timSend->stop();
    //             ui->chkTimSend->setChecked(false);
    //             ui->txtSendMs->setEnabled(true);
    //         }
    //         // 关闭串口并重置状态
    //         if (serialPort->isOpen())
    //         {
    //             serialPort->close();
    //         }

    //         // 更新UI
    //         ui->openBt->setText("打开串口");
    //         ui->serailCb->setEnabled(true);
    //         lblPortState->setText("DISCONNECTED");
    //         lblPortState->setStyleSheet("color:red");
    //         //弹出警告
    //         QMessageBox::warning
    //             (this, "连接中断", "检测到串口设备已断开！");
    //     }
//}
/*更新串口列表*/
void MainWindow::findSerial() {
    QStringList newPortStringList;
    newPortStringList.clear();
    foreach(const QSerialPortInfo & info, QSerialPortInfo::availablePorts()) {
        newPortStringList += info.portName();
    }
    //sort
    std::sort(newPortStringList.begin(), newPortStringList.end(), [this](const QString& a, const QString& b) {
        return naturalCompare(a, b);
    });
    if (newPortStringList.size() != portStringList.size())
    {
        portStringList = newPortStringList;
        ui->serailCb->clear();
        ui->serailCb->addItems(portStringList);
    }
}
//检测通讯端口槽函数
void MainWindow::on_btnSerialCheck_clicked()
{
    ui->serailCb->clear();
    //通过QSerialPortInfo查找可用串口
    foreach(const QSerialPortInfo & info, QSerialPortInfo::availablePorts())
    {
        ui->serailCb->addItem(info.portName());
    }
}

/*打开串口*/
void MainWindow::on_openBt_clicked()
{
    //setupSerialPort();
    QString portName = ui->serailCb->currentText();
    int baudRate = getBaudRate(ui->baundrateCb->currentText());
    int dataBits = getDataBits(ui->databitCb->currentText());
    int stopBits = getStopBits(ui->stopbitCb->currentText());
    int checkBits = getCheckBits(ui->checkbitCb->currentText());
    if (ui->openBt->text() == "打开串口")
    {
        QMetaObject::invokeMethod(worker,"openPort",Qt::QueuedConnection,
                                  Q_ARG(QString,portName),
                                  Q_ARG(int,baudRate),
                                  Q_ARG(int,dataBits),
                                  Q_ARG(int,stopBits),
                                  Q_ARG(int,checkBits));
        emit requestOpenPort(portName, baudRate, dataBits, stopBits, checkBits);
        // if (serialPort->open(QIODevice::ReadWrite) == true)
        // {
        //     ui->openBt->setText("关闭串口");
        //     // 让端口号下拉框不可选，避免误操作（选择功能不可用，控件背景为灰色）
        //     ui->serailCb->setEnabled(false);
        //     QString sm = "%1 OPENED, %2, 8, NONE, 1";
        //     QString status = sm.arg(serialPort->portName()).arg(serialPort->baudRate());
        //     lblPortState->setText(status);
        //     lblPortState->setStyleSheet("color:green");
        // }
        // else
        // {
        //     QMessageBox::critical(this, "错误提示", "串口打开失败！！！\r\n该串口可能被占用\r\n请选择正确的串口");
        // }
    }
    else
    {
        emit requestCancelFile();
        QMetaObject::invokeMethod(worker, "closePort", Qt::QueuedConnection);

        if (timSend->isActive())
        {
            timSend->stop();
            ui->chkTimSend->setChecked(false);
        }
        // serialPort->close();
        ui->openBt->setText("打开串口");
        // 端口号下拉框恢复可选，避免误操作
        ui->serailCb->setEnabled(true);
        //statusBar 状态栏显示端口状态
        // QString sm = "%1 CLOSED";
        // QString status = sm.arg(serialPort->portName());
        // lblPortState->setText(status);
        // lblPortState->setStyleSheet("color:red");
    }

}
/*封装hex校验*/
bool MainWindow::validateHex(const QString& input)
{
    static QRegularExpression hexRegExp("^[0-9A-Fa-f]+$");
    return !input.isEmpty() &&
           (input.length() % 2 == 0) &&
           hexRegExp.match(input).hasMatch();
}

/*发送数据*/
void MainWindow::on_sendBt_clicked()
{
    // if (!serialPort->isOpen())
    // {
    //     QMessageBox::warning(this, "错误", "请先打开串口");
    //     return;
    // }
    // if (serialPort->error() != QSerialPort::NoError)
    // {
    //     handleSerialError(serialPort->error());
    //     return;
    // }
    //bool isValid = true;

    if(!worker->isPortOpen()){
        handleError("串口未打开！");
        return;
    }
    QString input = ui->sendEdit->toPlainText().remove(QRegExp("[\\s]"));//移除所有空格和换行符
    if (input.isEmpty())
    {
        QMessageBox::warning(this, "警告", "发送框为空，无法发送数据！");
        if (timSend->isActive() && ui->chkTimSend->isChecked()) {
            timSend->stop();
            ui->chkTimSend->setChecked(false);
            //将光标挪到最前面
            QTextCursor cursor = ui->sendEdit->textCursor();
            cursor.movePosition(QTextCursor::Start);
            ui->sendEdit->setTextCursor(cursor);
        }
        return;
    }
    QByteArray array = formatSendData(input);
    QMetaObject::invokeMethod(worker, "sendData", Qt::QueuedConnection, Q_ARG(QByteArray, array));
}
// 封装发送数据格式化函数
QByteArray MainWindow::formatSendData(const QString& input){
    QByteArray array;
    //Hex复选框
    if (ui->chk_send_hex->isChecked())
    {
        /*if (!validateHex(input) && ui->chkTimSend->isChecked() == 1)
        {
            QMessageBox::warning(this, "错误", "当前数据格式不合法，无法启动自动发送！");
            ui->chkTimSend->setChecked(false); // 强制取消勾选
            return;
        }*/
        if (!validateHex(input))
        {
            QMessageBox::warning(this, "错误", "非法的HEX格式！");
            if (timSend->isActive())
            {
                timSend->stop();
                ui->chkTimSend->setChecked(false);
                ui->txtSendMs->setEnabled(true);
            }
            return  QByteArray();//??
        }
        array = QByteArray::fromHex(input.toUtf8());
    }
    else
    {
        array = input.toUtf8();
    }
    //添加换行逻辑
    if (ui->chk_send_line->isChecked())
    {
        array.append("\r\n");
    }
    return array;

    qDebug() << "array:" << array;
    //QMetaObject::invokeMethod(worker, "sendData", Qt::QueuedConnection, Q_ARG(QByteArray, array));
    // int bytesWritten = array.size();
    // updateSendCount(bytesWritten);

    //QMetaObject::invokeMethod(sendcount,"updateSendCount",Qt::QueuedConnection,Q_ARG(int,bytesWritten));

    //发送框内容清除空格和换行符
    // QString input = ui->sendEdit->toPlainText();
    // QRegularExpression re("\\s");
    // input = input.remove(re);//移除所有空格和换行符
    // if(input.isEmpty())
    // {
    //     QMessageBox::warning(this, "警告", "发送框为空，无法发送数据！");
    //     if(timSend->isActive() && ui->chkTimSend->isChecked()){
    //         timSend->stop();
    //         ui->chkTimSend->setChecked(false);
    //         //将光标挪到最前面
    //         QTextCursor cursor = ui->sendEdit->textCursor();
    //         cursor.movePosition(QTextCursor::Start);
    //         ui->sendEdit->setTextCursor(cursor);
    //     }
    //     return;
    // }
}
/*封装更新右下角状态栏发送计数*/
void MainWindow::updateSendCount(int bytesWritten) {
    // 发送字节计数并显示
    if (bytesWritten >= 0)
    {
        // 发送字节计数
        sendNum += bytesWritten;
        // 状态栏显示计数值
        setNumOnLabel(lblSendNum, "S: ", sendNum);
    }
    else if (bytesWritten == -1)
    {
        QMessageBox::critical(this, "错误提示", "数据发送失败！");
    }
}

// 状态栏标签显示计数值
void MainWindow::setNumOnLabel(QLabel* lbl, QString strS, long num)
{
    QString str = strS + QString::number(num);
    lbl->setText(str);
}
/*接收清空*/
void MainWindow::on_clearBt_clicked()
{
    ui->recvEdit->clear();
    // 清除发送、接收字节计数
    sendNum = 0;
    recvNum = 0;
    // 状态栏显示计数值
    setNumOnLabel(lblSendNum, "S: ", sendNum);
    setNumOnLabel(lblRecvNum, "R: ", recvNum);
}
/*发送清空*/
void MainWindow::on_btnClearSend_clicked()
{
    ui->sendEdit->clear();
    // 清除发送字节计数
    sendNum = 0;
    // 状态栏显示计数值
    setNumOnLabel(lblSendNum, "S: ", sendNum);
}
// 定时发送开关 选择复选框
void MainWindow::on_chkTimSend_stateChanged(int arg1)
{
    //QMutexLocker locker(&serialMutex);

    if (1)
    {
        // 获取复选框状态，未选为0，选中为2
        if (arg1 == 0)
        {
            timSend->stop();
            // if(FileSendTimer && FileSendTimer->isActive())
            // {
            //     FileSendTimer->stop();
            // }
            // for(int i = 0;i<10;++i)
            // {
            // 处理当前事件队列中的所有事件 因为发送文件时再勾选自动发送 取消掉时会有延迟
            QCoreApplication::processEvents();
            // }
            // 等待串口缓冲区清空
            // while (serialPort->bytesToWrite() > 0)
            // {
            //     QCoreApplication::processEvents();
            // }
            // serialPort->flush();
            // serialPort->clear();
            // 时间输入框恢复可选
            ui->txtSendMs->setEnabled(true);

        }
        else
        {
            // 对输入的值做限幅，小于10ms会弹出对话框提示
            if (ui->txtSendMs->text().toInt() >= 10)
            {
                timSend->start(ui->txtSendMs->text().toInt());// 设置定时时长，重新计数
                // 让时间输入框不可选，避免误操作（输入功能不可用，控件背景为灰色）
                ui->txtSendMs->setEnabled(false);
            }
            else
            {
                ui->chkTimSend->setCheckState(Qt::Unchecked);
                QMessageBox::critical(this, "错误提示", "定时发送的最小间隔为 10ms\r\n请确保输入的值 >=10");
            }
        }
    }
    else if (/*!serialPort->isOpen() &&*/ ui->chkTimSend->isChecked())
    {
        QMessageBox::warning(this, "错误", "串口未打开，无法开启定时发送");
        QTimer::singleShot(0, [this]() {
            ui->chkTimSend->setChecked(false);
        });
    }
}

void MainWindow::onSendBytesWritten(int bytesWritten)
{
    updateSendCount(bytesWritten);
}

//选择文件
void MainWindow::on_selectFileButton_clicked()
{
    if(m_isSendingFile)
    {
        emit requestCancelFile();
        ui->selectFileButton->setText("发送文件");
        ui->progressBar->setValue(0);//输入帧大小发送文件 暂停发送后将进度条设置0
        m_isSendingFile = false;
        return;
    }

    bool isOpen = false;
    QMetaObject::invokeMethod(worker, "isPortOpen", Qt::BlockingQueuedConnection,
                              Q_RETURN_ARG(bool, isOpen));

    if(!isOpen)
    {
        QMessageBox::warning(this,"错误","请先打开串口");
        return;
    }
    // if(ui->selectFileButton->text()=="发送文件"){
    //文件操作  文件打开
    QString curPath = QDir::currentPath();
    if(curPath.isEmpty()) return;
    QString dlgTitle = "打开文件";
    QString Filter = "文本文件(*.txt);;二进制文件(*.bin *.dat);;所有文件(*.*)";
    QString filepath = QFileDialog::getOpenFileName(this, dlgTitle, curPath, Filter);
    if(filepath.isEmpty()) return;

    int frameLen = ui->PackLen_lineEdit->text().toInt();
    int frameGap = ui->GapTim_lineEdit->text().toInt();

    if(frameLen < 0 || frameGap < 0 ) {
        QMessageBox::warning(this, "参数错误", "数值不能为负数");
        return;
    }

    m_isSendingFile = true;
    ui->selectFileButton->setText("停止发送");
    ui->progressBar->setValue(0);

    // 使用QMetaObject确保跨线程调用安全
    QMetaObject::invokeMethod(worker, "sendFile", Qt::QueuedConnection,
                              Q_ARG(QString, filepath),
                              Q_ARG(int, frameLen),
                              Q_ARG(int, frameGap));

}
void MainWindow::updateFileProgress(int percent)
{
    ui->progressBar->setValue(percent);
}

void MainWindow::onFileTransferFinished()
{
    m_isSendingFile = false;
    if(ui->selectFileButton->text() == "停止发送") {
        ui->selectFileButton->setText("发送文件");
    }
    //ui->progressBar->setValue(0);
}

// /*将文件内容加到发送框*/
// void MainWindow::displayFileInfoAndContent()
// {

//     QString info = QString("%1%2").arg("文件大小为：").arg(FileText.length());
//     ui->sendEdit->clear();
//     ui->sendEdit->append(info);
//     if (ui->chk_send_hex->isChecked())
//     {
//         ui->sendEdit->setPlainText(FileText.toUtf8().toHex(' ').toUpper());
//     }
//     else
//     {
//         ui->sendEdit->setPlainText(FileText);
//     }
//     ui->sendEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);
//     isSendFile = true;
//     FrameCount = 0;
//     ProgressBarValue = 0;
//     qDebug() << "displayFileInfoAndContent FileText.size:" << FileText.size();
// }
//保存文件
void MainWindow::on_SaveData_Button_clicked() {
    qDebug() << "Save data button clicked";
    QString data = ui->recvEdit->toPlainText();
    if (data.isEmpty())
    {
        QMessageBox::information(this, "提示", "数据内容空");
        return;
    }
    QString curPath = QDir::currentPath();
    QString dlgTitle = "保存文件";                     // 对话框标题
    QString filter = "文本文件(*.txt);;所有文件(*.*)";  // 文件过滤器
    QString filename = QFileDialog::getSaveFileName(this, dlgTitle, curPath, filter);
    if (filename.isEmpty())
    {
        return;
    }
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly))
    {
        return;
    }
    QTextStream stream(&file);
    stream << data;
    file.flush();
    file.close();
    qDebug()<<"主线程currentThread: "<<QThread::currentThread();;
}


// /*处理文件编码并读取*/
// void MainWindow::handleFileEncodingAndRead(QFile& file, const QFileInfo& fileinfo)
// {
//     // //编码判断
//     // //QTextCodec::setCodecForLocale(codec);
//     // //QByteArray data = file.readAll();
//     // QMetaObject::invokeMethod(worker,"recvData",Qt::QueuedConnection);
//     // //子线程接收的数据为data
//     // file.flush();
//     // file.close();
//     // //解码
//     // QTextCodec::ConverterState state;
//     // QTextCodec* codec = QTextCodec::codecForName("UTF-8");
//     // FileText = codec->toUnicode(data.constData(), data.size(), &state);//若有无效字符则是GBK编码;
//     // if (state.invalidChars > 0)
//     //     //转码后返回
//     //     FileText = QTextCodec::codecForName("GBK")->toUnicode(data);
//     // else
//     //     FileText = QString::fromUtf8(data);
//     // // 调用文件类型判断和读取函数
//     // handleFileTypeAndRead(fileinfo);
//     // qDebug() << "handleFileEncodingAndRead FileText.size:" << FileText.size();
// }
// /*处理文件类型*/
// void MainWindow::handleFileTypeAndRead(const QFileInfo& fileinfo) {
//     //文件读取
//     int type = 0;
//     QMimeDatabase db;
//     QMimeType mime = db.mimeTypeForFile(fileinfo.filePath());
//     if (mime.name().startsWith("text/"))
//     {
//         type = 1;
//     }
//     else if (mime.name().startsWith("application/"))
//     {
//         type = 2;
//     }

//     switch (type)
//     {
//     case 1:
//     {
//         if (FileText.isEmpty())
//         {
//             QMessageBox::information(this, "提示", "文件内容为空");
//             return;
//         }
//     }
//     break;
//     case 2:
//     {
//         int filelen = fileinfo.size();
//         QVector<char> cBuf(filelen);//?
//         QFile file(fileinfo.filePath());
//         if (file.open(QIODevice::ReadOnly))
//         {
//             QDataStream datain(&file);
//             datain.readRawData(&cBuf[0], filelen);
//             file.flush();
//             file.close();
//             FileText = QString::fromLocal8Bit(&cBuf[0], filelen);
//         }
//     }
//     break;
//     }
//     // 显示文件大小信息和内容
//     displayFileInfoAndContent();
//     qDebug() << "handleFileTypeAndRead FileText.size:" << FileText.size();
// }
// /*发送文件*/
// void MainWindow::SendFile()
// {
//     FrameLen = ui->PackLen_lineEdit->text().toInt();
//     FrameGap = ui->GapTim_lineEdit->text().toInt();
//     int textlen = FileText.size();
//     qDebug() << "FrameLen.size" << FrameLen;
//     qDebug() << "FrameGap.size" << FrameGap;
//     if (FrameGap <= 0 || textlen <= FrameLen)
//     {
//         QMetaObject::invokeMethod(worker, "sendData", Qt::QueuedConnection, Q_ARG(QByteArray, FileText.toUtf8()));
//         ui->selectFileButton->setText("发送文件");//
//     }
//     else
//     {
//         // 按设定时间和长度发送
//         FrameNumber = textlen / FrameLen; // 包数量
//         LastFrameLen = textlen % FrameLen; // 最后一包数据长度
//         if (FrameNumber >= 100)
//         {
//             ProgressBarStep = FrameNumber / 100;
//         }
//         else
//         {
//             ProgressBarStep = 100 / FrameNumber;
//         }
//         FileSendTimer = new QTimer(this);
//         connect(FileSendTimer, &QTimer::timeout, this, &MainWindow::File_TimerSend);
//         FileSendTimer->start(FrameGap);
//         if (ui->sendEdit->toPlainText().isEmpty())
//         {
//             if (!sendEmptyPrompted) {
//                 QMessageBox::warning(this, "警告", "发送框为空，无法发送数据！");
//                 sendEmptyPrompted = true;
//                 ui->chkTimSend->setChecked(false);
//             }
//             return;
//         }
//     }
// }
// /*按帧大小 帧间隔发送文件*/
// void MainWindow::File_TimerSend()
// {
//     if (ui->sendEdit->toPlainText().isEmpty())
//     {
//         QMessageBox::warning(this, "警告", "发送框内容为空");
//         FileSendTimer->stop();
//         ui->selectFileButton->setText("发送文件");
//         return;
//     }
//     if (FrameCount < FrameNumber)
//     {
//         qDebug() << "FrameCount: " << FrameCount;
//         qDebug() << "FrameNumber: " << FrameNumber;
//         QByteArray frameData = FileText.mid(FrameCount * FrameLen, FrameLen).toUtf8();

//         //int bytesWritten = serialPort->write(frameData);
//         QMetaObject::invokeMethod(worker, "sendData", Qt::QueuedConnection, Q_ARG(QByteArray, frameData));
//         // int bytesWritten = FileText.size();
//         // qDebug() << "byteWritten: " << bytesWritten;
//         // updateSendCount(bytesWritten);
//         // if(bytesWritten >= 0)
//         // {
//         //     updateSendCount(bytesWritten);
//         // }
//         FrameCount++;
//         ui->progressBar->setValue(ProgressBarValue += ProgressBarStep);
//     }
//     else
//     {
//         if (LastFrameLen > 0)
//         {
//             QByteArray lastframeData = FileText.mid(FrameCount * FrameLen, LastFrameLen).toUtf8();
//             //int bytesWritten = serialPort->write(lastframeData);
//             QMetaObject::invokeMethod(worker, "sendData", Qt::QueuedConnection, Q_ARG(QByteArray, lastframeData));
//             // int bytesWritten = array.size();
//             // updateSendCount(bytesWritten);
//             // if(bytesWritten >= 0)
//             // {
//             //     updateSendCount(bytesWritten);
//             // }
//             //serialPort->write(FileText.mid(FrameCount * FrameLen, LastFrameLen).toUtf8());
//         }
//         ui->progressBar->setValue(100);
//         QMessageBox::information(this, "提示", "发送完成");

//         FileSendTimer->stop();
//         FrameCount = 0;
//         ProgressBarValue = 0;
//         FrameNumber = 0;
//         LastFrameLen = 0;
//         ui->progressBar->setValue(0);
//         ui->selectFileButton->setText("发送文件");
//     }
// }
